//app.js
App({
  onLaunch: function () {
    // 展示本地存储能力
    //var logs = wx.getStorageSync('logs') || []
    //logs.unshift(Date.now())
    //wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        this.get({
          url:'/stu/login/wx',
          data:{code:res.code},
          hasLoading:false
        }).then(result=>{
          
          if(result.data.success){
            if(result.cookies && result.cookies.length){
              let cookie = result.cookies[0].split(";")[0].trim();            
              this.globalData["Cookie"]=cookie;
            }
      
            this.globalData.currUser = result.data.data;//记录当前用户
            
            setTimeout(()=>{
              wx.navigateTo({
                url: '../hw/hw'
              });
            },1500);
          }
        });
      }
    })

    /*
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo

              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    });
    */


    wx.getSystemInfo({
      success: e => {
        this.globalData.StatusBar = e.statusBarHeight;
        let custom = wx.getMenuButtonBoundingClientRect();
        this.globalData.Custom = custom;  
        this.globalData.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
      }
    });



  },

  globalData: {
    userInfo: null,
    baseUrl:'https://my-course.top',
    currUser:null,
  },
  
  getHeader (){
    if(this.globalData["Cookie"]){
      return {                   
        "Cookie":this.globalData["Cookie"]  
       };
    }
    return {};
  },

  upload(options){
    
    const promise = new Promise((resolve,reject)=>{

      try{
       
        wx.showLoading({
          title:'处理中...',
        });             
  
        const _options = {...options};
    
        _options["url"] = `${this.globalData.baseUrl}${options.url}`;
        _options["header"] = this.getHeader();
       
        if(options.header){
          _options["header"] = Object.assign(_options["header"],options.header);
        }
    
        _options["success"]= res => {
          console.log('--------上传文件接口调用成功--------');
          console.log(res);
          if(res.statusCode==200){        
            const result = JSON.parse(res.data);
    
            if(result.logined===false){
              wx.showModal({
                title: '错误',
                content: "请登录！",
                showCancel:false
              });
              return;
            }            
            if(result.success !== true && result.success !== false){
              wx.showModal({
                title: '错误',
                content: "接口数据格式错误！",
                showCancel:false
              });
              return;
            }
            if(result.success){

              setTimeout(()=>{
                wx.showToast({
                  title: result.message,
                  icon: 'success',
                  duration: 2000,
                  success(){
                      resolve(res);            
                  }
                });
              },500);
                
              
              
            }else{            
              reject(result);            
            }     
    
          }else{  
          
            wx.showModal({
              title: '错误',
              content: '错误代码：'+res.statusCode,
              showCancel:false
            });  
           
          }
          
        };
    
        _options['fail'] = (res)=>{
          console.log('--------上传文件接口调用失败--------');
          console.log(res);
          wx.showModal({
            title: '错误',
            content:  '接口调用失败',
            showCancel:false
          });
        };
    
        _options['complete'] = (res)=>{
          console.log('--------上传文件接口调用完成--------');
          console.log(res);
          wx.hideLoading();
          
          
        };
    
        
        wx.uploadFile(_options);
  
      }catch(e){
        
        console.log(e);
        wx.showModal({
          title: '错误',
          content: "系统错误！",
          showCancel:false
        });
      }

      
    });

    return promise;

  },

  request(options){
    
    options.hasLoading = (options.hasLoading !== true && options.hasLoading !== false) ? true : options.hasLoading;
    
    const promise = new Promise((resolve,reject)=>{

      try{

        if(options.hasLoading){
          wx.showLoading({
            title:'处理中...',
          });
        }       
  
        const _options = {...options};
    
        _options["url"] = `${this.globalData.baseUrl}${options.url}`;
        _options["header"] = this.getHeader();
       
        if(options.header){
          _options["header"] = Object.assign(_options["header"],options.header);
        }
    
        _options["success"]= res => {
          
          if(res.statusCode==200){        
            const data = res.data;
    
            if(data.logined===false){
              wx.showModal({
                title: '错误',
                content: "请登录！",
                showCancel:false
              });
              return;
            }
            
            if(resolve){            
              resolve(res);
            }
    
          }else{  
          
            wx.showModal({
              title: '错误',
              content: '错误代码：'+res.statusCode,
              showCancel:false
            });  
           
          }
          
        };
    
        _options['fail'] = (res)=>{
          wx.showModal({
            title: '错误',
            content: "调用接口失败！",
            showCancel:false
          });
        };
    
        _options['complete'] = (res)=>{
          if(options.hasLoading){
            wx.hideLoading();
          }
          
        };
    
        
        wx.request(_options);
  
      }catch(e){
        
        console.log(e);
        wx.showModal({
          title: '错误',
          content: "系统错误！",
          showCancel:false
        });
      }

      
    });

    return promise;

  },

  get(options){
    options.method="GET";    
    return this.request(options);    
  },

  opr(options){

    return new Promise((resolve,reject)=>{

      this
        .request(options)
        .then(res=>{
          const result = res.data;
          if(result.success !== true && result.success !== false){
            wx.showModal({
              title: '错误',
              content: "接口数据格式错误！",
              showCancel:false
            });
            return;
          }
          if(result.success){
            wx.showToast({
              title: result.message,
              icon: 'success',
              duration: 1500,
              success(){
                if(resolve){
                  resolve(res);
                }                
              }
            });
          }else{            
            reject(res);            
          }          
        });

    });
  },

  post(options){
    options.method="POST";
    return this.opr(options);    
  },

  put(options){
    options.method="PUT";
    return this.opr(options); 
  },

  delete(options){
    options.method="DELETE";
    return this.opr(options); 
  },



})